﻿using MesBSW.BLL.Mes;
using MesBSW.DAL.MesDB;
using MesBSW.DAL.MesDTO;
using MesBSW.Tools;
using SqlSugar;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Windows.Forms;

namespace MesBSW.View.Mes
{
    public partial class SiteInfoGroupSettingFrm : UIForm
    {
        #region "内部变量"
        private SiteControler _ctrl = new SiteControler();
        private List<SiteInfo> _site_list = new List<SiteInfo>();
        private SiteGroupDTO _curr_dto = null;
        private SqlSugarClient Db = SqlSugares.GetInstance();
        #endregion

        public SiteInfoGroupSettingFrm(SiteGroupDTO groupDTO)
        {
            InitializeComponent();
            
            //初始化站点树
            var publicValues = new List<int>();
            //查询公共部门，并获取到公共部门的站点
            var list = Db.Context.SqlQueryable<object>($@"select
	            id
            from
	            base_dept
            where
	            is_public = 1").ToList();
            dynamic dylist = list;
            for(int i = 0;i< list.Count;i++)
            {
                publicValues.Add(dylist[i].id);
            }
            publicValues.Add(groupDTO.deptId);
            this._site_list = _ctrl.SearchAllStieInfo().Where(item => publicValues.Contains(item.deptId)).ToList();
            this.InitSiteInfoTreeView();

            //传入当前操作的站点组别
            this._curr_dto = groupDTO;
            if (this._curr_dto.SiteInfoList != null)
            {
                foreach (var item in this._curr_dto.SiteInfoList)
                {
                    item.RowStatus = "NotChange";
                }
            }
            this.txtGroupCode.Text = groupDTO.GroupCode;
            this.txtGroupName.Text = groupDTO.GroupName;
            if (groupDTO.IsDel == 1)
            {
                this.rbnIsDel.Checked = true;
                this.rbnNotDel.Checked = false;
            }
            else
            {
                this.rbnIsDel.Checked = false;
                this.rbnNotDel.Checked = true;
            }
            this.InitSiteGroupDataGridView(this._curr_dto);
        }

        #region "控件事件"
        /// <summary>
        /// 添加站点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAddSite_Click(object sender, EventArgs e)
        {
            if (this.tvwSiteInfo.SelectedNode != null && this._site_list != null && this._site_list.Count > 0)
            {
                var query = this._site_list.Where(s => s.ID == int.Parse(this.tvwSiteInfo.SelectedNode.Tag.ToString()));
                if (query != null && query.Count() > 0)
                {
                    SiteInfo tmpSiteInfo = query.First();
                    Boolean isEx = false;

                    if (isEx)
                    {
                        UIMessageBox.ShowWarning("站点：" + tmpSiteInfo.SiteName + "已经在该组别中存在，不能添加！");
                    }
                    else
                    {
                        SiteInfoGroupDTO tmpBean = new SiteInfoGroupDTO();
                        tmpBean.ID = 0;
                        tmpBean.SiteID = tmpSiteInfo.ID;
                        tmpBean.GroupID = this._curr_dto.ID;
                        tmpBean.RowStatus = "Add";
                        tmpBean.SiteInfo = tmpSiteInfo;
                        this._curr_dto.SiteInfoList.Add(tmpBean);
                        this.ResetSort();
                        this.InitSiteGroupDataGridView(this._curr_dto);
                        UIMessageTip.ShowOk("站点已经添加到组别中！");
                    }
                }
            }
            else
            {
                UIMessageBox.ShowWarning("请先在左边列表中选择站点后再按【新增站点】！");
            }
        }

        /// <summary>
        /// 移除站点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDelSite_Click(object sender, EventArgs e)
        {
            if (this.dgvSiteInfo.SelectedCells.Count > 0)
            {
                DataRow tmpRow = (this.dgvSiteInfo.Rows[this.dgvSiteInfo.SelectedCells[0].RowIndex].DataBoundItem as DataRowView).Row;
                int tmpId = int.Parse(tmpRow["site_id"].ToString());
                if (this._curr_dto.SiteInfoList != null && this._curr_dto.SiteInfoList.Count > 0)
                {
                    var query = this._curr_dto.SiteInfoList.Where(s => s.SiteID == tmpId);
                    if (query != null && query.Count() > 0)
                    {
                        SiteInfoGroupDTO tmpBean = query.First();
                        tmpBean.RowStatus = "Delete";
                        this._curr_dto.SiteInfoList.Remove(tmpBean);
                        this.ResetSort();
                        this.InitSiteGroupDataGridView(this._curr_dto);
                        UIMessageTip.ShowOk("站点已经移出！");
                    }
                }
            }
            else
            {
                UIMessageBox.ShowWarning("请选择站点后再移除站点！");
            }
        }

        /// <summary>
        /// 上移站点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnUp_Click(object sender, EventArgs e)
        {
            if (this.dgvSiteInfo.SelectedCells.Count > 0)
            {
                DataRow tmpRow = (this.dgvSiteInfo.Rows[this.dgvSiteInfo.SelectedCells[0].RowIndex].DataBoundItem as DataRowView).Row;
                int siteID = int.Parse(tmpRow["site_id"].ToString());
                SiteInfoGroupDTO tmpBean = null;
                if (this._curr_dto.SiteInfoList != null && this._curr_dto.SiteInfoList.Count > 0)
                {
                    int tmpSort = -999;
                    for (int i = 0; i < this._curr_dto.SiteInfoList.Count; i++)
                    {
                        if (this._curr_dto.SiteInfoList[i].SiteID == siteID)
                        {
                            tmpSort = i;
                            tmpBean = this._curr_dto.SiteInfoList[i];
                        }
                    }


                    if (tmpSort == 0)
                    {
                        UIMessageBox.ShowWarning("该站点已经在第一位，无法上移！");
                    }
                    else if (tmpSort > 0)
                    {
                        this._curr_dto.SiteInfoList.Remove(tmpBean);
                        this._curr_dto.SiteInfoList.Insert(tmpSort - 1, tmpBean);
                    }
                }
                this.ResetSort();
                this.InitSiteGroupDataGridView(this._curr_dto);
            }
            else
            {
                UIMessageBox.ShowWarning("请选择站点后再移除站点！");
            }
        }

        /// <summary>
        /// 下移站点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDown_Click(object sender, EventArgs e)
        {
            if (this.dgvSiteInfo.SelectedCells.Count > 0)
            {
                DataRow tmpRow = (this.dgvSiteInfo.Rows[this.dgvSiteInfo.SelectedCells[0].RowIndex].DataBoundItem as DataRowView).Row;
                int siteID = int.Parse(tmpRow["site_id"].ToString());
                SiteInfoGroupDTO tmpBean = null;
                if (this._curr_dto.SiteInfoList != null && this._curr_dto.SiteInfoList.Count > 0)
                {
                    int tmpSort = -999;
                    for (int i = 0; i < this._curr_dto.SiteInfoList.Count; i++)
                    {
                        if (this._curr_dto.SiteInfoList[i].SiteID == siteID)
                        {
                            tmpSort = i;
                            tmpBean = this._curr_dto.SiteInfoList[i];
                        }
                    }


                    if (tmpSort == this._curr_dto.SiteInfoList.Count)
                    {
                        UIMessageBox.ShowWarning("该站点已经在最后，无法下移！");
                    }
                    else if (tmpSort >= 0)
                    {
                        this._curr_dto.SiteInfoList.Remove(tmpBean);
                        this._curr_dto.SiteInfoList.Insert(tmpSort + 1, tmpBean);
                    }
                }

                this.ResetSort();
                this.InitSiteGroupDataGridView(this._curr_dto);
            }
            else
            {
                UIMessageBox.ShowWarning("请选择站点后再移除站点！");
            }
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (this._curr_dto.SiteInfoList != null && this._curr_dto.SiteInfoList.Count > 0)
            {
                try
                {
                    this._curr_dto.GroupName = this.txtGroupName.Text.Trim();
                    if (this.rbnIsDel.Checked == true)
                    {
                        this._curr_dto.IsDel = 1;
                    }
                    else 
                    {
                        this._curr_dto.IsDel = 0;
                    }
                    int count = this._ctrl.SaveSiteInfoGroup(this._curr_dto);
                    if (count > 0)
                    {
                        UIMessageBox.ShowSuccess("站点组信息保存成功！");
                    }
                    else
                    {
                        UIMessageBox.ShowError("站点组信息保存失败！");
                    }
                }
                catch (Exception ex)
                {
                    UIMessageBox.ShowError("站点组信息保存失败！" + "\r\n" + ex.Message);
                }
            }
            else
            {
                UIMessageBox.ShowError("没有任何可以保存的站点信息！");
            }
        }
        #endregion

        #region "内部方法"
        /// <summary>
        /// 初始化站点树
        /// </summary>
        private void InitSiteInfoTreeView()
        {
            this.tvwSiteInfo.Nodes.Clear();
            if (this._site_list != null && this._site_list.Count > 0)
            {
                TreeNode parentNode = new TreeNode();
                parentNode.Text = "根站点";
                parentNode.Tag = 0;
                this.InitChildNode(ref parentNode, this._site_list);

                this.tvwSiteInfo.Nodes.Add(parentNode);
                this.tvwSiteInfo.ExpandAll();
            }
        }

        /// <summary>
        /// 站点树添加子节点
        /// </summary>
        /// <param name="parentNode"></param>
        /// <param name="siteList"></param>
        private void InitChildNode(ref TreeNode parentNode, List<SiteInfo> siteList)
        {
            if (parentNode != null)
            {
                List<SiteInfo> childList = null;
                int tmpID = int.Parse(parentNode.Tag.ToString());
                childList = siteList.Where(s => s.ParentID == tmpID).ToList();
                if (childList != null && childList.Count > 0)
                {
                    foreach (var item in childList)
                    {
                        TreeNode childNode = new TreeNode();
                        childNode.Text = item.SiteName;
                        childNode.Tag = item.ID;
                        parentNode.Nodes.Add(childNode);
                        if (item.IsFinal != 1)
                        {
                            this.InitChildNode(ref childNode, siteList);
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 列出组别中的站点列表
        /// </summary>
        /// <param name="groupBean"></param>
        private void InitSiteGroupDataGridView(SiteGroupDTO groupBean)
        {
            DataTable tmpDt = new DataTable();
            tmpDt.Columns.Add("id");
            tmpDt.Columns.Add("site_id");
            tmpDt.Columns.Add("site_code");
            tmpDt.Columns.Add("site_name");
            tmpDt.Columns.Add("site_sn");
            tmpDt.Columns.Add("parent_id");
            tmpDt.Columns.Add("is_del");
            tmpDt.Columns.Add("is_del_name");
            tmpDt.Columns.Add("group_id");
            tmpDt.Columns.Add("sort");
            tmpDt.Columns.Add("is_last");
            tmpDt.Columns.Add("is_last_name");
            tmpDt.Columns.Add("row_status");

            if (groupBean != null && groupBean.SiteInfoList != null && groupBean.SiteInfoList.Count > 0)
            {
                foreach (var infoBean in groupBean.SiteInfoList.OrderBy(s => s.Sort).ToList())
                {
                    DataRow dr = tmpDt.NewRow();
                    dr["id"] = infoBean.ID;
                    dr["site_id"] = infoBean.SiteID;
                    dr["site_code"] = infoBean.SiteInfo.SiteCode;
                    dr["site_name"] = infoBean.SiteInfo.SiteName;
                    dr["site_sn"] = infoBean.SiteInfo.SiteShortName;
                    dr["parent_id"] = infoBean.SiteInfo.ParentID;
                    dr["is_del"] = infoBean.SiteInfo.IsDel;
                    dr["is_del_name"] = false;
                    if (infoBean.SiteInfo.IsDel == 1)
                    {
                        dr["is_last_name"] = true;
                    }
                    dr["group_id"] = infoBean.GroupID;
                    dr["sort"] = infoBean.Sort;
                    dr["is_last"] = infoBean.IsLast;
                    dr["is_last_name"] = false;
                    if (infoBean.IsLast == 1)
                    {
                        dr["is_last_name"] = true;
                    }
                    dr["row_status"] = infoBean.RowStatus;
                    tmpDt.Rows.Add(dr);
                }
            }
            this.dgvSiteInfo.DataSource = tmpDt;
        }

        /// <summary>
        /// 重新将站点排序，并将排在最后的站点设成最终站点
        /// </summary>
        private void ResetSort()
        {
            if (this._curr_dto.SiteInfoList != null && this._curr_dto.SiteInfoList.Count > 0)
            {
                for (int i = 0; i < this._curr_dto.SiteInfoList.Count; i++)
                {
                    SiteInfoGroupDTO tmpBean = this._curr_dto.SiteInfoList[i];
                    tmpBean.Sort = i + 1;
                    if (i == this._curr_dto.SiteInfoList.Count - 1)
                    {
                        tmpBean.IsLast = 1;
                    }
                    else
                    {
                        tmpBean.IsLast = 0;
                    }
                }
            }
        }
        #endregion
    }
}
